<template>
  <div>
    <el-dialog
        v-model="visible"
        top="5vh"
        width="680px"
        :show-close="false"
        :close-on-click-modal="false"
        :title="title"
        :before-close="handleClose"
        class="child-operate-dialog"
        destroy-on-close
    >
      <el-form
          ref="childFormRef"
          :rules="rules"
          :model="childForm" v-loading="loading"
          class="child-form">
        <div class="display-flex child-base-info">
          <el-form-item>
            <img :src="childForm.avatarUrl" style="line-height: 1.42857143;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    height: 100px;
    width: 100px;padding: 4px;">
          </el-form-item>
          <div class="add-margin-l-50">
            <el-form-item prop="lastName" :label="$t('loc.lastName')" required>
              <el-input :placeholder="$t('loc.lastName')" v-model="childForm.lastName" type="text" autocomplete="off"/>
            </el-form-item>
            <el-form-item prop="firstName" :label="$t('loc.1stName')" required>
              <el-input :placeholder="$t('loc.1stName')" v-model="childForm.firstName" type="text" autocomplete="off"/>
            </el-form-item>
            <el-form-item prop="gender" :label="$t('loc.gender')" required>
              <el-radio-group v-model="childForm.gender">
                <el-radio :label="$t('loc.male')" size="large">{{ $t('loc.male') }}</el-radio>
                <el-radio :label="$t('loc.female')" size="large">{{ $t('loc.female') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        <el-divider v-if="childId"/>
        <div v-if="childId">
          <div class="flex-space-between">
            <div>{{ $t('loc.Parents') }}</div>
            <div>
              <el-button type="primary" v-if="false">{{ $t('loc.ivtPts') }}</el-button>
            </div>
          </div>
          <div style="overflow-y: auto;max-height: 100px;background-color: #f0f3f4;padding: 5px;">
            <div v-for="parent in parentList" style="display: flex;
    justify-content: space-between;">
              <div>
                {{ parent.displayName }}
                  <el-tag
                      type="info"
                      effect="plain"
                      round>{{ parent.email || parent.phoneNumber }}</el-tag>
              </div>
              <div>
                <el-tag type="success">{{ $t('loc.parentConnect') }}</el-tag>
              </div>
            </div>
            <div v-if="parentList.length === 0 ">
              <div class="text-center">
                {{ $t('loc.noPnt') }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="childId">
          <div class="flex-space-between add-padding-t-12">
            <div>可使用的邀请码</div>
            <el-button @click="generateCode">生成邀请码</el-button>
          </div>
          <div>
              <div style="background-color: #f0f3f4;padding: 5px;max-height: 130px;overflow: auto;">
                <el-tag v-for="code in pendingCode" @close="closeCodeHandler(code)" effect="dark" type="success" class="add-margin-bt5" style="margin-right: 5px" closable>{{ code }}</el-tag>
              </div>
          </div>
        </div>
        <el-divider/>
        <el-form-item :label="$t('loc.birthDay')" prop="birthDate" class="child-birthDay">
          <el-date-picker
              v-model="childForm.birthDate"
              type="date"
              :placeholder="$t('loc.birthDay')"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div class="flex-align-justify">
          <el-form-item :label="$t('loc.emtDate')" prop="enrollmentDate" required>
            <el-date-picker
                v-model="childForm.enrollmentDate"
                type="date"
                :placeholder="$t('loc.emtDate')"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item prop="withdrawnDate" :label="$t('loc.wtdDate')">
            <el-date-picker
                v-model="childForm.withdrawnDate"
                type="date"
                :placeholder="$t('loc.wtdDate')"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>
        <el-form-item :label="$t('loc.childCenter')" required>
          <el-select v-model="currentSchoolId" @change="selectGroupChange" class="m-2" placeholder="Select"
                     size="large">
            <el-option
                v-for="item in canSchools"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('loc.childClass')" required>
          <el-select v-model="currentGroupId" @change="selectGroupChange" class="m-2" placeholder="Select" size="large">
            <el-option
                v-for="item in canGroups"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('loc.rateFwk')" required>
          <el-select v-model="frameworkId" @change="selectGroupChange" class="m-2" placeholder="Select"
                     size="large">
            <el-option
                v-for="item in frameworksOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="childId" :label="$t('loc.activePd')" required>
          <el-select v-model="alias" @change="selectGroupChange" class="m-2" placeholder="Select"
                     size="large">
            <el-option
                v-for="item in [{id:'2023-2024 学年'}]"
                :key="item.id"
                :label="item.id"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
          <el-button @click="handleClose">{{ $t('loc.cancel') }}</el-button>
          <el-button :loading="submitLoading" type="primary" @click="submitHandler">
             {{ $t('loc.submit') }}
          </el-button>
      </span>
      </template>
    </el-dialog>
  </div>

</template>

<script>
import ChildApi from '@/api/child'
import ParentApi from '@/api/parent'
import moment from "moment";
import { RefreshRight } from '@element-plus/icons-vue'
import SvgIcon from '@jamescoyle/vue-icon';
import { mdiRefresh } from '@mdi/js';
import {Frameworks} from "@/utils/constants.js";

export default {
  name: "ChildEditDialog",
  props: ['dialogVisible', 'childId', 'groupId'],
  components: {RefreshRight,SvgIcon},
  data() {
    let enrollmentDateValidator = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('loc.notEmpty')));
      } else {
        callback();
      }
    };
    let withdrawnDateValidator = (rule, value, callback) => {
      // 离校日期不能早于入学日期
      let withdrawnDate = moment(value);
      let enrollmentDate = moment(this.childForm.enrollmentDate);
      if (value && enrollmentDate && withdrawnDate.isBefore(enrollmentDate)) {
        callback(new Error('离校时间不能早于入学时间'));
      } else {
        callback();
      }
    };
    let birthDateValidator = (rule, value, callback) => {
      // 生日不能大于入学时间和退学时间不能大于当前时间
      if (!value) {
        callback(new Error(this.$t('loc.birthdayNotEmpty')));
        return
      }
      let birthDate = moment(value);
      let enrollmentDate = this.childForm.enrollmentDate ? moment(this.childForm.enrollmentDate) : null;
      let withdrawnDate = this.childForm.withdrawnDate ? moment(this.childForm.withdrawnDate) : null;
      if (enrollmentDate && birthDate.isAfter(enrollmentDate)) {
        callback(new Error('生日不能晚于入学时间'));
      } else if (withdrawnDate && birthDate.isAfter(withdrawnDate)) {
        callback(new Error('生日不能晚于离校时间'));
      } else {
        callback();
      }
    };
    return {
      mdiRefresh: mdiRefresh,
      visible: false,
      loading: false,
      childForm: {},
      childEntity: {},
      submitLoading: false,
      schools: [],
      currentSchoolId: '',
      currentGroupId: '',
      pendingCode: [],
      needReLoadData: false,
      frameworkId: '',
      alias: '2023-2024 学年',
      rules: {
        enrollmentDate: [
          {required: true, validator: enrollmentDateValidator, trigger: 'change'},
        ],
        withdrawnDate: [
          {required: false, validator: withdrawnDateValidator, trigger: 'change'},
        ],
        birthDate: [
          {required: true, validator: birthDateValidator, trigger: 'change'},
        ],
      }
    }
  },
  watch: {
    dialogVisible: function (val) {
      this.visible = val;
      if (val) {
        this.initData()
      }
    },
  },
  computed: {
    currentUser() {
      return this.$store.state.user.currentUser
    },
    title() {
      return this.childId ? this.$t('loc.editChildIfo') : this.$t('loc.addChild')
    },
    parentList() {
      return this.childForm.parents || []
    },
    canSchools() {
      // 过滤掉已经沒有班级的幼儿园
      return this.schools.filter(item => item.groups.length > 0)
    },
    frameworksOptions() {
      return Frameworks
    },
    canGroups() {
      let currentSchool = this.schools.find(item => item.id === this.currentSchoolId) || {}
      let groups = currentSchool.groups || []
      return groups.filter(group => group.isInactive !== true)
    },
  },
  methods: {
    initData() {
      this.childForm = {}
      this.pendingCode = []
      this.loadChildData()
      this.loadSetSchoolAndGroup()
    },
    loadChildData() {
      if (this.childId) {
        this.loading = true
        ChildApi.getChild(this.childId).then(res => {
          this.childForm = res
          this.currentSchoolId = res.group.schoolId
          this.currentGroupId = res.group.id
          this.pendingCode = this.childForm.invitationCodes ? this.childForm.invitationCodes.map(item=>item.token) : []
          this.frameworkId = res.frameworkId
          this.loading = false
        }).catch(error => {
          this.$message.error(error.response.data.description)
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.childForm = {
          avatarUrl: 'https://d2urtjxi3o4r5s.cloudfront.net/images/child_avatar.png',
          gender: this.$t('loc.male')
        }
      }
    },
    loadSetSchoolAndGroup() {
      this.setSchoolAndGroupLoading = true
      ChildApi.getSetSchoolAndGroup(this.childId).then(res => {
        this.schools = res
        if (!this.currentSchoolId) {
          this.currentSchoolId = this.schools[0].id || ''
        }
        if (!this.currentGroupId && this.schools[0].groups.length > 0) {
          this.currentGroupId = this.schools[0].groups[0].id || ''
        }
        let currentSchool = this.schools.find(school => {
          return school.groups.find(group => group.id === this.groupId)
        })
        if (this.groupId && currentSchool) {
          this.currentGroupId = this.groupId
          // 從this.schools 找到groupId 所在的schoolId
          this.currentSchoolId = currentSchool.id
        }
      }).catch(error => {
        console.log(error)
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.setSchoolAndGroupLoading = false
      })
    },
    handleClose() {
      this.visible = false
      this.$emit('update:dialogVisible', this.visible)
      if (this.needReLoadData === true) {
        this.needReLoadData = false
        this.$emit('needReLoadData')
      }
    },

    submitHandler() {
      if (this.submitLoading) {
        return
      }
      this.$refs['childFormRef'].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let param = {
            firstName: this.childForm.firstName.trim(),
            lastName: this.childForm.lastName.trim(),
            groupId: this.currentGroupId,
            gender: this.childForm.gender,
            avatarMediaId: '',
            birthDate: this.childForm.birthDate,
            enrollmentDate: this.childForm.enrollmentDate,
            withdrawnDate: this.childForm.withdrawnDate,
            frameworkId: this.frameworkId
          }

          console.log(param)
          if (this.childId) {
            param.childId = this.childId
            ChildApi.updateChild(param).then(res => {
              this.needReLoadData = true
              this.handleClose()
            }).catch(error => {
              this.$message.error(error.response.data.description)
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            ChildApi.createChild(param).then(res => {
              this.needReLoadData = true
              this.handleClose()
            }).catch(error => {
              this.$message.error(error.response.data.description)
            }).finally(() => {
              this.submitLoading = false
            })
          }
        }
      })

    },
    selectGroupChange() {
      let school = this.canSchools.find(item => item.id === this.currentSchoolId)
      let group = school.groups.find(item => item.id === this.currentGroupId)
      if (!group) {
        this.currentGroupId = school.groups[0].id
      }
    },
    generateCode () {
      let childIds = [this.childId]
      let userId = this.currentUser.userId
      if (!childIds || childIds.length === 0 || !userId) {
        console.log('参数错误')
        return
      }
      let params = {
        childIds: childIds,
        userId: userId
      }
      this.generateCodeLoading = true
      ParentApi.generateParentsCode(params).then(res => {
        this.$message.success('生成成功')
        console.log(res.childCodesMap[this.childId])
        this.pendingCode.push(...res.childCodesMap[this.childId])
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.generateCodeLoading = false
      })
    },
    closeCodeHandler(code) {
      this.submitLoading = true
      ParentApi.deleteParentCode(code).then(res => {
        this.$message.success('删除成功')
        this.pendingCode = this.pendingCode.filter(item => item !== code)
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.submitLoading = false
      })
    }
  },
}
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  border-bottom: 0 !important;
  padding-bottom: 0;
}

.child-operate-dialog {
  /deep/ .el-dialog__body {
    padding: 0;
  }
}

.child-form {
  padding: 15px;
  background-color: #fff;
  border: 1px solid #dee5e7;
  border-radius: 2px;

  /deep/ .el-form-item {
    margin-bottom: 10px;
  }

  .child-base-info {
    /deep/ .el-form-item__content {
      margin-left: 50px;
    }

    /deep/ .el-input__wrapper {
      flex-direction: row-reverse;
    }
  }

  .child-birthDay {
    /deep/ .el-date-editor {
      width: 100%;
    }
  }

  /deep/ .el-select {
    width: 100%;
  }
}
</style>